package com.canyou.utils;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author cd 下载文件辅助类
 */
@Slf4j
public final class DownloadUtils {

    private DownloadUtils() {
    }

    /**
     * 下载文件
     *
     * @param file        文件
     * @param fileName    文件名称
     * @param contentType 类型
     */
    public static void downFile(File file, String fileName, String contentType, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", contentType);
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("filename", URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Access-Control-Expose-Headers", "filename");
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            IoUtil.close(fis);
            IoUtil.close(bis);
        }
    }
}
